Pro im_process

;This program is a consolidation of four steps in image processing.
;First, the skys are assembled and median'd.
;Second, the corresponding duration darks (median) is called up..
;Third, the median sky is made into a flat field by subtracting the
;median dark and then normalized with the mean pixel value.
;Finally, the object images are sky subtracted and flat fielded.
;Product is a set of images ready to inspect and stack.
;The procedure is intended as a "pipeline" for NIR dither patterns.


;get filenames of image files to be processed
filenames = dialog_pickfile(/multiple_files, filter = '*.fits', $
                            title = 'FITS files (images) to be processed')
;how many images?
nimages = n_elements(filenames)

;get filename of sky file for subtracting from images
sky = dialog_pickfile(title = 'Median sky FITS file', filter = '*.fits')

;get filename of dark file for flat field
dark = dialog_pickfile(title = 'Dark FITS file', filter = '*.fits')

;get path where dark-subtracted files are to be written
ds_path = dialog_pickfile(title = $
                          'Choose directory to write dark-subracted FITS', $
                          /directory)
;read in sky image, convert to float
sky = double(mrdfits(sky, 0, skyhead, /unsigned))

;atv,sky
;stop

;read in dark image, convert to float
dark = double(mrdfits(dark, 0, darkhead, /unsigned))

FOR i = 0, nimages-1 DO BEGIN   ;for each image file
;read in image, conver to float; get header as well
   image = double(mrdfits(filenames[i], 0, header, /unsigned))
;subtract sky image
   image_ss = image-sky
;flat field image

;print,mean(sky-dark)
;atv, (sky-dark)/mean(sky-dark)
;stop

   image_ss_ff = image_ss / ((sky-dark)/double(mean(sky-dark)))
;strip directory path from image filename (oth element)
   file_nopath = reverse(strsplit(filenames[i], '/', /extract))
;strip off .fits suffix
   file_begin = strsplit(file_nopath[0], '.fits', /extract, /regex)
;add write path and _pro.fits suffix

   pro_filename = file_begin[0] + '_pro.fits'

;write processed image and original image header to file
   print, 'WRITING TO ' + pro_filename
   mwrfits, image_ss_ff, pro_filename, header
ENDFOR

END
